<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Search, Refresh, Delete, Edit } from '@element-plus/icons-vue'
import { queryPageApi, updateStatusApi, deleteBatchApi } from '@/api/maintenance'
// 引入获取保养员API
import { getMaintenanceStaffApi } from '@/api/maintenance'

// 搜索条件
const searchParams = ref({
  userName: '',
  plateNumber: '',
  status: '',
  dateRange: [],
  beginDate: '',
  endDate: ''
  
})

// 监听日期范围变化
watch(
  () => searchParams.value.dateRange,
  (newValue) => {
    if(newValue.length === 2){
      searchParams.value.beginDate = newValue[0]
      searchParams.value.endDate = newValue[1]
    } else {
      searchParams.value.beginDate = ''
      searchParams.value.endDate = ''
    }
  }
)

// 预约状态选项
const statusOptions = ref([
  { label: '待确认', value: '待确认' },
  { label: '已确认', value: '已确认' },
  { label: '工作中', value: '工作中' },
  { label: '已完成', value: '已完成' },
  { label: '已取消', value: '已取消' }
])

// 保养员选项（job_id=3且status='空闲'的员工）
const maintenanceStaffOptions = ref([
  { label: '不分配', value: '' }
])

// 获取保养员列表
const fetchMaintenanceStaff = async () => {
  try {
    // 调用后端API获取job_id=3且status='空闲'的员工
    const result = await getMaintenanceStaffApi()
    
    if(result.code) {
      // 处理API返回的数据，转换为选择器需要的格式
      // 后端返回的数据结构: [{id, empName, jobId, status}, ...]
      const staffList = result.data.map(item => ({
        label: item.empName, // 显示名称
        value: item.empName  // 值也使用姓名，与后端保持一致
      }))
      
      // 添加空值选项供用户选择"不分配"
      maintenanceStaffOptions.value = [
        { label: '不分配', value: '' },
        ...staffList
      ]
    } else {
      ElMessage.error(result.msg || '获取保养员列表失败')
      // 出错时至少保留'不分配'选项
      maintenanceStaffOptions.value = [{ label: '不分配', value: '' }]
    }
  } catch (error) {
    console.error('获取保养员列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    // 出错时至少保留'不分配'选项
    maintenanceStaffOptions.value = [{ label: '不分配', value: '' }]
  }
}

// 分页配置
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const appointmentList = ref([])

// 选中的ID列表
const selectedIds = ref([])

// 操作对话框
const dialogVisible = ref(false)
const dialogTitle = ref('更新状态')
const currentAppointment = ref({})

onMounted(() => {
  fetchMaintenanceStaff()
  handleSearch()
})

// 查询数据
const handleSearch = async () => {
  try {
    const result = await queryPageApi(
      searchParams.value.userName,
      searchParams.value.plateNumber,
      searchParams.value.status,
      searchParams.value.beginDate,
      searchParams.value.endDate,
      currentPage.value - 1,
      pageSize.value
    )
    
    if(result.code) {
      // 直接使用后端返回的数据，不设置默认值
      appointmentList.value = result.data.rows
      total.value = result.data.total
      console.log('appointmentList:', appointmentList.value)
    } else {
      ElMessage.error(result.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 重置搜索条件
const handleReset = () => {
  searchParams.value = {
    userName: '',
    plateNumber: '',
    status: '',
    dateRange: [],
    beginDate: '',
    endDate: ''
  }
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 处理复选框选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 更新预约状态
const handleUpdateStatus = (row) => {
  currentAppointment.value = { ...row }
  dialogVisible.value = true
}

// 保存状态更新
const saveStatus = async () => {
  try {
    // 直接传递所有参数，包括可能为空的empName
    const result = await updateStatusApi({
      id: currentAppointment.value.id,
      status: currentAppointment.value.status,
      empName: currentAppointment.value.empName || ''
    })
    
    if(result.code) {
      ElMessage.success('状态更新成功')
      dialogVisible.value = false
      handleSearch()
      // 重新获取保养员列表，更新空闲状态
      fetchMaintenanceStaff()
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 批量删除
const handleBatchDelete = () => {
  if(selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的预约记录')
    return
  }
  
  ElMessageBox.confirm('确定删除选中的预约记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 将数组转换为逗号分隔的字符串
      const result = await deleteBatchApi(selectedIds.value.join(','))
      if(result.code) {
        ElMessage.success('删除成功')
        handleSearch()
        selectedIds.value = []
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('网络错误，请稍后重试')
    }
  })
}

// 单行删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该预约记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const result = await deleteBatchApi(id.toString())
      if(result.code) {
        ElMessage.success('删除成功')
        handleSearch()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('网络错误，请稍后重试')
    }
  })
}

// 根据状态获取标签类型
const getTagType = (status) => {
const typeMap = {
'待确认': 'warning',
'已确认': 'primary',
'工作中': 'info',
'已完成': 'success',
'已取消': 'danger'
};
return typeMap[status] || 'info';
};

// 格式化状态显示
const formatStatus = (status) => {
const statusMap = {
'待确认': '待确认',
'已确认': '已确认',
'工作中': '工作中',
'已完成': '已完成',
'已取消': '已取消'
};
return statusMap[status] || status;
};

// 获取状态文本（用于对话框显示）
const getStatusText = (status) => {
return formatStatus(status);
};
</script>

<template>
  <h1>保养预约管理</h1> 
  <br>
  
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchParams" class="search-form">
    <el-form-item label="用户姓名">
      <el-input v-model="searchParams.userName" placeholder="请输入用户姓名"></el-input>
    </el-form-item>
    
    <el-form-item label="车牌号">
      <el-input v-model="searchParams.plateNumber" placeholder="请输入车牌号"></el-input>
    </el-form-item>
    
    <el-form-item label="预约状态">
      <el-select v-model="searchParams.status" placeholder="请选择" style="width: 120px;">
        <el-option label="全部" value=""></el-option>
        <el-option v-for="option in statusOptions" :key="option.value" 
                  :label="option.label" :value="option.value"></el-option>
      </el-select>
    </el-form-item>
    
    <el-form-item label="预约日期">
      <el-date-picker
        v-model="searchParams.dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>查询
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>清空
      </el-button>
    </el-form-item>
  </el-form>
  
  <!-- 操作按钮 -->
  <el-button type="danger" @click="handleBatchDelete">
    <el-icon><Delete /></el-icon>批量删除
  </el-button>
  <br><br>
  
  <!-- 数据表格 -->
  <el-table :data="appointmentList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center"></el-table-column>
    <el-table-column type="index" label="序号" width="60" align="center"/>
    <el-table-column prop="userName" label="用户姓名" width="120" align="center"></el-table-column>
    <el-table-column prop="plateNumber" label="车牌号" width="100" align="center"></el-table-column>
    <el-table-column prop="appointmentDate" label="预约日期" width="100" align="center"></el-table-column>
    <el-table-column prop="description" label="保养描述" width="250" align="center"></el-table-column>
    <el-table-column prop="createdAt" label="创建时间" width="170" align="center"></el-table-column>
    <el-table-column label="预约状态" width="85" align="center">
      <template #default="scope">
        <el-tag :type="getTagType(scope.row.status)">{{ formatStatus(scope.row.status) }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="empName" label="保养员" width="100" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
          <el-button size="small" type="primary" @click="handleUpdateStatus(scope.row)">
            <el-icon><Edit /></el-icon>更新状态
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
    </el-table-column>
  </el-table>
  <br>
  
  <!-- 分页组件 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[5, 10, 20, 30]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  ></el-pagination>
  
  <!-- 更新状态对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="currentAppointment" label-width="80px">
      <el-form-item label="预约ID">
        <el-input v-model="currentAppointment.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户姓名">
        <el-input v-model="currentAppointment.userName" disabled></el-input>
      </el-form-item>
      <el-form-item label="车牌号">
        <el-input v-model="currentAppointment.plateNumber" disabled></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="currentAppointment.contactPhone" disabled></el-input>
      </el-form-item>
      <el-form-item label="当前状态">
        <el-input :value="formatStatus(currentAppointment.status)" disabled></el-input>
      </el-form-item>
      <el-form-item label="新状态" required>
        <el-select v-model="currentAppointment.status" placeholder="请选择新状态" style="width: 100%;">
          <el-option v-for="option in statusOptions" :key="option.value" 
                    :label="option.label" :value="option.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保养员">
        <el-select v-model="currentAppointment.empName" placeholder="请选择保养员" style="width: 100%;">
          <el-option v-for="option in maintenanceStaffOptions" :key="option.value" 
                    :label="option.label" :value="option.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStatus">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>